/**
 * 样衣初选单
 */
import * as React from 'react'
import { Card, Button, Form, Row, Col, Cascader, Modal, Input, message } from 'antd'
import Authentication from '../../router/Authentication'
import { PageHeaderLayout, StandardTable, Zmage } from '../../components'
import '../../assets/style/TableList.less'
import { get, SEND_SAMPLE } from '../../service/api'
const FormItem = Form.Item

export interface State {
  formValues: any
  pagination: any
  selectedRows: any []
  visible: boolean
}
const SendSample = Form.create()((props: any) => {
  const { form, visible, modelVisible, handleSubmit } = props
  const { getFieldDecorator } = form
  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  }
  const okHandle = () => {
    form.validateFields((err: any, fieldsValue: any) => {
      if (err) return
      form.resetFields()
      handleSubmit(fieldsValue)
    });
  };
  return (
    <Modal
      title="样衣邮寄"
      width={450}
      visible={visible}
      onOk={okHandle}
      onCancel={() => modelVisible(false)}>
        <FormItem {...formItemLayout} label="快递公司">
          {getFieldDecorator('expressName', {
              rules: [{required: true, message: '请输入快递公司!',}],
          })(<Input />)}
        </FormItem>
        <FormItem {...formItemLayout} label="快递单号">
          {getFieldDecorator('expressId', {
              rules: [{required: true, message: '请输入快递单号!',}],
          })(<Input />)}
        </FormItem>
    </Modal>
  )
})

@Authentication
class Primary extends React.Component<any, State> {
  
  state = {
    pagination: {},
    formValues: {},
    selectedRows: [],
    visible: false
  }
  componentDidMount () {
    this.search({}, {})
  }

  handleFormReset = () => {
    const { form } = this.props
    form.resetFields()
    this.setState({
      formValues: {}
    })
    this.search({}, {})
  }
  /**
   * 点击查询按钮
   */
  handleSearch = (e: any) => {
    e.preventDefault()
    const { form, data: { pagination } } = this.props
    form.validateFields((err: any, fieldsValue: any) => {
      if (err) return
      Object.assign(fieldsValue,{pageIndex: pagination.current})
      Object.assign(fieldsValue,{pageSize: pagination.pageSize})
      this.setState({
        formValues: fieldsValue,
        pagination,
      })
      this.search({
        ...fieldsValue
      }, pagination)
    })
  }
  /**
   * 调用查询方法
   */
  search (param: any , pageInfo: any) {
    const { list } = this.props
    const { pagination, formValues } = this.state
    list(param||formValues, pageInfo||pagination)
  }
  renderSimpleForm() {
    const { form, categorys } = this.props
    const { getFieldDecorator } = form
    getFieldDecorator('dlid', { initialValue: [] })
    getFieldDecorator('xlid', { initialValue: [] })
    const changeCateGorys = (e: string []) => {
      let dlid = e[0]
      let xlid = ''
      if (e.length>1) xlid = e[1]
      form.setFieldsValue({
        dlid,
        xlid
      })
    }
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="编码">
              {getFieldDecorator('sampleid')(
                <Input placeholder="请输入编码"/>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="波段">
              {getFieldDecorator('band')(
                <Input placeholder="请输入波段"/>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="分类">
              <Cascader options={categorys} onChange = {changeCateGorys} changeOnSelect placeholder="请选择分类"/>
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span className="submitButtons">
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    )
  }
  /**
   * 筛选或者更改分页
   */
  handleStandardTableChange = (pagination: any, filtersArg: any, sorter: any) => {
    const { formValues } = this.state
    let params: any = formValues
    params = {
      ...params,
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
    }
    this.setState({
      formValues: params,
      pagination,
    })
    this.search(params, pagination)
  }
  //编辑
  handleInfo = (no: string, id: string) => {
    const { record } = this.props
    record({ id, no })
    this.props.history.push({ pathname: '/first/edit' })
  }
  //选中事件
  handleSelectRows = (rows: any []) => {
    this.setState({
      selectedRows: rows,
    })
  }
  //显示隐藏框
  modelVisible = (visible: boolean) => {
    this.setState({
      ...this.state,
      visible
    })
  }
  //发货
  handleSendSample = (filed: any) => {
    const { selectedRows } = this.state
    let ids: any [] = new Array()
    selectedRows.map((row: any) => {
      ids = [...ids, row.sampleid]
    })
    get(SEND_SAMPLE, {
      ids: ids.join(','),
      ...filed
    }).then((res => {
      if (res.code == '1') {
        message.success('操作成功！')
        this.modelVisible(false)
        this.search({}, {})
      }
      else message.error(res.errMsg)
    }))
  }
  render () {
    const { loading, data } = this.props
    const { selectedRows, visible } = this.state
    const columns: any [] = [
      {
        title: '照片',
        dataIndex: 'img1',
        key: 'img1',
        width: '200px',
        align: 'center',
        render: (text: string, record: any) => <Zmage style={{ width: "80px" }} src={text}/>,
      }, {
        title: '样衣编号',
        dataIndex: 'sampleid',
        key: 'sampleid'
      },{
        title: '大类',
        dataIndex: 'dlid',
        key: 'dlid'
      }, {
        title: '品类',
        dataIndex: 'xlid',
        key: 'xlid'
      }, {
        title: '波段',
        dataIndex: 'bandname',
        key: 'bandname'
      }, {
        title: '货号',
        dataIndex: 'pcode',
        key: 'pcode'
      }, {
        title: '发货数量',
        dataIndex: 'sendqty',
        key: 'sendqty'
      }, {
        title: '收货数量',
        dataIndex: 'recqty',
        key: 'recqty'
      },{
        title: '快递单号',
        dataIndex: 'expno',
        key: 'expno'
      },{
        title: '快递单号',
        dataIndex: 'expcompany',
        key: 'expcompany'
      },{
        title: '供应商名称',
        dataIndex: 'supplierid',
        key: 'supplierid'
      }, {
        title: '状态',
        dataIndex: 'postflag',
        key: 'postflag',
        render: (text: string) => text=="0"?"未发货":text=="1"?"已发货":"已收货",
      },{
        title: '操作',
        width: '150px',
        render: (row: any) => (
          <React.Fragment>
            <a onClick={ () => this.handleInfo(row.id, row.sampleid)}>编辑</a>
          </React.Fragment>
        ),
      },
    ]
    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div className="tableList">
            <div className="tableListForm">{this.renderSimpleForm()}</div>
            <div className="tableListOperator">
              {selectedRows.length > 0 && (
                <span>
                  <Button type="primary" onClick= {() =>this.modelVisible(true)}>发货</Button>
                </span>
              )}
            </div>
            <StandardTable
            xscroll="1500px"
              rowKey = "id"
              selectedRows = {selectedRows}
              select = {true}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <SendSample
          visible = {visible}
          modelVisible = {this.modelVisible}
          handleSubmit = {this.handleSendSample}/>
      </PageHeaderLayout>
    )
  }
}

export default Form.create()(Primary)